package com.onec.service.manage.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.onec.service.api.component.EmailUtils;
import com.onec.service.api.content.PatternUtil;
import com.onec.service.api.enums.StatusEnum;
import com.onec.service.api.enums.error.ManageErrorEnum;
import com.onec.service.api.exception.ManageException;
import com.onec.service.manage.component.EmailContent;
import com.onec.service.manage.dao.*;
import com.onec.service.manage.dto.req.UserInfoReq;
import com.onec.service.manage.entity.*;
import com.onec.service.manage.service.UserLoginService;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * 运营登录sevice
 *
 * @author ONEC
 */
@Service
public class UserLoginServiceImpl implements UserLoginService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserLoginServiceImpl.class);

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleInfoMapper roleInfoMapper;
    @Autowired
    private PermissionInfoMapper permissionInfoMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    EmailContent emailContent;

    @Autowired
    EmailUtils emailUtils;


    @Autowired
    private UserTokenMapper userTokenMapper;

    @Override
    public UserInfo findUserById(Long userId) {
        return userInfoMapper.selectUserById(userId, StatusEnum.SUCCESS);
    }

    /**
     * 登录验证获取用户信息
     *
     * @param username
     * @return saleInfo
     */
    @Override
    public UserInfo findUserName(String username) {
        // 邮箱验证
        LOGGER.info("管理系统登录用户参数：{}", username);
        UserInfo userInfo;
        if (username.matches(PatternUtil.EMAIL)) {
            userInfo = userInfoMapper.selectUserByEmail(username);
        } else if (username.matches(PatternUtil.PHONE)) {
            userInfo = userInfoMapper.selectUserByPhone(username);
        } else {
            userInfo = userInfoMapper.selectUserByName(username);
        }
        return userInfo;
    }

    /**
     * 添加用户
     *
     * @param userInfoReq
     * @return SaleInfo
     */
    @Override
    public UserInfo saveUserInfo(UserInfoReq userInfoReq) {

        // 验证用户名！
        if (existUserName(userInfoReq.getUserName())) {
            throw new ManageException(ManageErrorEnum.EXIST_USER_NAME);
        }
        // 验证用户名！
        if (existEmail(userInfoReq.getEmail())) {
            throw new ManageException(ManageErrorEnum.EXIST_EMAIL);
        }    // 验证用户名！
        if (existPhone(userInfoReq.getPhone())) {
            throw new ManageException(ManageErrorEnum.EXIST_PHONE);
        }
        String salt = RandomUtil.randomString(32);
        ByteSource byteSource = ByteSource.Util.bytes(salt);
        String passwordRandom = RandomUtil.randomString(16);
        LOGGER.info("默认密码：{}", passwordRandom);

        String password = new SimpleHash("MD5", passwordRandom, byteSource, 1024).toHex();
        UserInfo userInfo = new UserInfo();
        userInfo.setUserNo(RandomUtil.randomString(12));
        userInfo.setVersion(1);

        userInfo.setSalt(salt);
        userInfo.setPassword(password);
        userInfo.setStatus(StatusEnum.SUCCESS);

        userInfo.setUserName(userInfoReq.getUserName());
        userInfo.setPhone(userInfoReq.getPhone());
        userInfo.setEmail(userInfoReq.getEmail());

        userInfo.setCreateTime(DateUtil.date());
        userInfo.setUpdateTime(DateUtil.date());
        userInfoMapper.insertUserInfo(userInfo);
        LOGGER.info("用户{}:设置成功：", userInfo.getUserName());

        // 设置默认角色
        UserRole userRole = new UserRole();
        userRole.setUserId(userInfo.getId());
        userRole.setRoleId(1L);
        userRole.setRemark("设置默认角色");
        userRoleMapper.insertUserRole(userRole);
        LOGGER.info("用户：{}:默认角色设置成功", userInfo.getUserName());

        List<String> emailList = Collections.singletonList(userInfo.getEmail());
        String content = emailContent.getRegister().replace("!!!", passwordRandom);
        emailUtils.send("账户激活通知", content, emailList);

        // 发送密码邮件！
        return userInfo;
    }

    @Override
    public List<UserRole> findUserRoleByUserId(Long userId) {
        return userRoleMapper.selectByUserId(userId);
    }

    @Override
    public RoleInfo findRoleByRoleId(Long roleId) {
        return roleInfoMapper.selectRoleById(roleId, StatusEnum.SUCCESS);
    }

    @Override
    public List<RolePermission> findRolePermissionByRoleId(Long roleId) {
        return rolePermissionMapper.selectByRoleId(roleId);
    }

    @Override
    public PermissionInfo findPermissionById(Long id) {
        return permissionInfoMapper.selectPermissionById(id, StatusEnum.SUCCESS);
    }

    @Override
    public boolean existPhone(String phone) {
        return userInfoMapper.updateByPhone(DateUtil.date(), phone) == 1;
    }


    @Override
    public boolean existUserName(String userName) {
        return userInfoMapper.updateByUserName(DateUtil.date(), userName) == 1;
    }

    /**
     * @param email
     * @return true 证明存在
     */
    @Override
    public boolean existEmail(String email) {
        return userInfoMapper.updateByEmail(DateUtil.date(), email) == 1;
    }


}
